import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# 1. 读取并排序
df = pd.read_excel(
    "Monthly_Counts_Quad&Event.xlsx",
    sheet_name="EventRootCode",
    parse_dates=["Month"]
)
df = df.sort_values("Month")

# 2. 全局字体：Times New Roman
plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.serif']  = ['Times New Roman']

# 3. 公共参数
months     = df["Month"]
start_base = pd.Timestamp("2014-01-01")
end_base   = df["Month"].max()
buffer     = pd.Timedelta(days=15)

# 4. 配色：使用 tab20 调色板中的前 20 种颜色
cmap = plt.get_cmap('tab20')
colors = [cmap(i) for i in range(20)]

# 5. 子图布局：4 行 × 5 列
fig, axes = plt.subplots(4, 5, figsize=(18, 12), sharex=True, sharey=True)
axes = axes.flatten()

# 6. 循环绘制 "01"–"20" 列
codes = [f"{i:02d}" for i in range(1, 21)]
for idx, (ax, code) in enumerate(zip(axes, codes)):
    ax.plot(
        months, df[code].astype(float),
        color=colors[idx], linewidth=1.5
    )
    # 缓冲首尾
    ax.set_xlim(start_base - buffer, end_base + buffer)
    # 主刻度：1、5、9 月
    ax.xaxis.set_major_locator(
        mdates.MonthLocator(bymonth=range(1, 13, 6))
    )
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
    # 次刻度：每月
    ax.xaxis.set_minor_locator(mdates.MonthLocator())
    # 网格
    ax.grid(which='major', axis='both', linestyle='--', linewidth=0.5)
    # 子图标题
    ax.set_title(f"Code {code}", fontfamily='Times New Roman', fontsize=10)

# 7. 旋转并缩小底部 X 轴标签字体
for ax in axes[-5:]:
    plt.setp(
        ax.get_xticklabels(),
        rotation=30,
        ha='right',
        fontsize=4  # 缩小字体
    )

plt.tight_layout()

# —— 你可以在这里或之后添加统一的外层标签和大标题 ——
# fig.text(0.5, 0.04, "Month", ha='center', fontfamily='Times New Roman')
# fig.text(0.04, 0.5, "Count", va='center', rotation='vertical', fontfamily='Times New Roman')
# fig.suptitle("EventRootCode 各类别时间序列（2014-01 起）",
#              fontfamily='Times New Roman', fontsize=14)

fig.savefig('EventRootCode_300dpi.jpg', dpi=300)
plt.show()
